package com.kime.email.book;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Properties;

/**
 * Java 邮件开发详解
 * 创建一封 HTML 格式的邮件
 */
public class HtmlMessage {
    public static void main(String[] args) throws Exception {
        String from = "kimewen@163.com";
        String to   = "kimewen@qq.com";
        String subject = "test";
        String body = "<h4>欢迎大家阅读此邮件</h4><a href='https://www.baidu.com'>访问百度</a>";
        // 创建 Session 实例对象
        Session session = Session.getDefaultInstance(new Properties());
        // 创建 MimeMessage 实例对象
        MimeMessage mimeMessage = new MimeMessage(session);
        // 设置发件人
        mimeMessage.setFrom(new InternetAddress(from));
        // 设置收件人
        mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        // 设置发送日期
        mimeMessage.setSentDate(new Date());
        // 设置邮件主题
        mimeMessage.setSubject(subject);
        // 设置 HTML 格式的邮件正文
        mimeMessage.setContent(body, "text/html;charset=gb2312");
        // 保存并生成最终的邮件内容
        mimeMessage.saveChanges();
        // 把 mimeMessage 对象中的内容写入到文件中
        mimeMessage.writeTo(new FileOutputStream("D:\\workspace\\email-demo\\src\\main\\resources\\eml\\htmlMessage.eml"));
    }
}
